package beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.faces.bean.ManagedBean;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;

@ManagedBean(name = "doutoradoFora")
public class DoutoradoForaBean {

	private List<Prof> profs = new ArrayList<Prof>();

	public DoutoradoForaBean() {
		String serviceURI = "http://grupo03.mooo.com/grupo03/query";
		String queryString = "PREFIX grupo03:<http://www.owl-ontologies.com/Ontology1307822014.owl#> ";
		queryString += "PREFIX dbpedia: <http://dbpedia.org/resource/> ";
		queryString += "PREFIX dbpedia-owl: <http://dbpedia.org/ontology/> ";
		queryString += "PREFIX dbpd: <http://dbpedia.org/property/> ";
		queryString += "SELECT ?t ?cidade ?pais ?pais2 ";
		queryString += "WHERE{ ";
		queryString += "?prof grupo03:nome ?t. ";
		queryString += "?prof grupo03:cidadeDoutorado ?cidade ";
		queryString += "OPTIONAL{ ";
		queryString += "SERVICE<http://dbpedia.org/sparql>{ ";
		queryString += "?cidade dbpedia-owl:country ?pais ";
		queryString += "OPTIONAL{ ";
		queryString += "?cidade dbpd:country ?pais2  ";
		queryString += "} ";
		queryString += "} ";
		queryString += "} ";
		queryString += "OPTIONAL{ ";
		queryString += "SERVICE<http://dbpedia.org/sparql>{ ";
		queryString += "?cidade dbpd:country ?pais2 ";
		queryString += "} ";
		queryString += "} ";
		queryString += "} ";

		Query query = QueryFactory.create(queryString);

		QueryExecution qe = QueryExecutionFactory.sparqlService(serviceURI,
				query);
		ResultSet results = qe.execSelect();
		while (results.hasNext()) {
			QuerySolution solution = results.next();
			Iterator<String> iter = solution.varNames();
			while (iter.hasNext()) {
				System.out.println(iter.next());
			}
			if (solution.getResource("pais") != null) {
				profs.add(new Prof(solution.getLiteral("t").getString(),
						solution.getResource("pais").getLocalName()));
			} else {
				if (solution.getLiteral("pais2") != null) {
					profs.add(new Prof(solution.getLiteral("t").getString(),
							solution.getLiteral("pais2").getString()));
				} else {
					profs.add(new Prof(solution.getLiteral("t").getString(),
							"NEM TEM"));
				}
			}
		}
		List<Prof> aux = new ArrayList<Prof>();
		for (int i = 0; i < profs.size(); i++) {
			if (!profs.get(i).getCidade().equals("Brazil")) {
				aux.add(profs.get(i));
			}
		}
		profs = aux;
	}

	public List<Prof> getProfs() {
		return profs;
	}

	public void setProfs(List<Prof> profs) {
		this.profs = profs;
	}

}
